﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace BinaryTools {
    public partial class ConversionControl : UserControl {
        private bool _inUpdateNumber;

        public ConversionControl() {
            InitializeComponent();
        }

        private void _binary_TextChanged(object sender, EventArgs e) {
            try {
                UpdateNumber(Convert.ToInt32(_binary.Text, 2));
                _binary.ForeColor = Color.Black;
            } catch {
                _binary.ForeColor = Color.Red;
            }
        }

        private void _octal_TextChanged(object sender, EventArgs e) {
            try {
                UpdateNumber(Convert.ToInt32(_octal.Text, 8));
                _octal.ForeColor = Color.Black;
            } catch {
                _octal.ForeColor = Color.Red;
            }
        }

        private void _decimal_TextChanged(object sender, EventArgs e) {
            try {
                UpdateNumber(Convert.ToInt32(_decimal.Text, 10));
                _decimal.ForeColor = Color.Black;
            } catch {
                _decimal.ForeColor = Color.Red;
            }
        }

        private void _hexadecimal_TextChanged(object sender, EventArgs e) {
            try {
                UpdateNumber(Convert.ToInt32(_hexadecimal.Text, 16));
                _hexadecimal.ForeColor = Color.Black;
            } catch {
                _hexadecimal.ForeColor = Color.Red;
            }
        }

        private void _character_KeyPress(object sender, KeyPressEventArgs e) {
            UpdateNumber((int)e.KeyChar);
            e.Handled = true;
        }

        private void UpdateNumber(int i) {
            if (!_inUpdateNumber) {
                try {
                    _inUpdateNumber = true;
                    _binary.Text = Convert.ToString(i, 2);
                    _octal.Text = Convert.ToString(i, 8);
                    _decimal.Text = Convert.ToString(i, 10);
                    _hexadecimal.Text = Convert.ToString(i, 16);
                    _character.Text = string.Format("{0}", (char)i);
                } finally {
                    _inUpdateNumber = false;
                }
            }
        }
    }
}